import axios from "axios";
import { getToken } from "~/utils/auth.js";
import { ERRORNotification } from "~/utils/utils.js";
import { message, emitter } from "~/utils/utils.js";
import { ElMessageBox } from "element-plus";
import { useUserCenter } from "~/pinia/useUserCenter.js";

const service = axios.create({
  baseURL: "/api",
});

let acitveAxios = 0;
let timer;
const showLoading = () => {
  acitveAxios++;
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      emitter.emit("showLoading");
    }
  }, 400);
};

const closeLoading = () => {
  acitveAxios--;
  if (acitveAxios <= 0) {
    clearTimeout(timer);
    emitter.emit("closeLoading");
  }
};

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    if (!config.donNotShowLoading) {
      showLoading();
    }
    // 在发送请求之前做些什么
    const token = getToken("token");
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  function (error) {
    if (!error.config.donNotShowLoading) {
      closeLoading();
    }
    message(error, "error");
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    const user = useUserCenter();
    if (!response.config.donNotShowLoading) {
      closeLoading();
    }
    if (response.headers["new-token"]) {
      user.setToken(response.headers["new-token"]);
    }
    if (response.data.code != 200) {
      if (response.data.code == 10103) {
        message("登录已过期，请重新登录", "warning");
        user.logoutWithoutApi();
        return Promise.reject(Error("登录已过期，请重新登录"));
      }
      ERRORNotification(response.data.msg, response.data.real_err);
      return Promise.reject(response.data.msg);
    } else {
      return response.data.data;
    }
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
  },
  function (error) {
    if (!error.config.donNotShowLoading) {
      closeLoading();
    }
    if (!error.response) {
      ElMessageBox.confirm(
        `
        <p>检测到请求错误</p>
        <p>${error}</p>
        `,
        "请求报错",
        {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: "稍后重试",
          cancelButtonText: "取消",
        }
      );
      return;
    }
    ERRORNotification("请求失败", error.response.statusText);
    return Promise.reject(error);
  }
);

export default service;
